package com.encrypt.encrptspringbootstarter.interceptor;
import java.util.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryption {
    private static final String ALGORITHM = "AES/CBC/PKCS5Padding";
    private static final String SECRET_KEY = "1234567890123456"; // 16 bytes key
    private static final String IV = "1234567890123456"; // 16 bytes IV

    public static String encrypt(String data) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] encrypted = cipher.doFinal(data.getBytes());
        return Base64.getEncoder().encodeToString(encrypted);
    }

    public static String decrypt(String encryptedData) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        IvParameterSpec ivParameterSpec = new IvParameterSpec(IV.getBytes());
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
        byte[] original = cipher.doFinal(Base64.getDecoder().decode(encryptedData));
        return new String(original);
    }

    public static String encryptDecrypt(String input, char key,char key2) {
        StringBuilder output = new StringBuilder();
        for (int i = 0; i < input.length(); i++) {
            output.append((char) (input.charAt(i) ^ key^ key2));
        }
        return output.toString();
    }
    public static String encryptDecrypt(String input) {
       return encryptDecrypt(input,'k','v');
    }

    public static void main(String[] args) {
        String plainText = "你好,中国";
        String plainText2 = "你好";

        char key = 'K'; // 选择一个密钥字符
        char key2 ='v';
        String encryptedText = encryptDecrypt(plainText, key, key2);
        String encryptedText2 = encryptDecrypt(plainText2, key, key2);

        System.out.println("Encrypted Text: " + encryptedText);
        System.out.println("Encrypted Text: " + encryptedText2);

        String decryptedText = encryptDecrypt(encryptedText, key, key2);
        String decryptedText2 = encryptDecrypt(encryptedText2, key, key2);

        System.out.println("Decrypted Text: " + decryptedText);
        System.out.println("Decrypted Text: " + decryptedText2);
    }
}